#include "ul_util.h"
#include <sys/time.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <poll.h>
#include "ul_define.h"


void LinuxNetworkUtility::ul_usleep(int64_t sleep_us)
{
  struct timeval interval;
  if (sleep_us > 0)
  {
    interval.tv_sec = sleep_us/1000000;
    interval.tv_usec = sleep_us%1000000;
    while (select(0,NULL,NULL,NULL,&interval) != 0)
    {
    }
  }
}



bool LinuxNetworkUtility::ul_check_fd_readable(const int fd, const int64_t timeout_us)
{
  bool result = false;
  struct pollfd poll_fd;
  int event_num = 0;
  int64_t l_timeout_ms = timeout_us;
  if(l_timeout_ms <= 0)
  {
    l_timeout_ms = 0;
  }
  else
  {
    l_timeout_ms = (timeout_us + 999)/1000;
  }
  if(fd > 0)
  {
    poll_fd.fd = fd;
    poll_fd.events = POLLIN;
    errno = 0;
    event_num = poll(&poll_fd,1,l_timeout_ms);
    if(0 < event_num)
    {
      result = (poll_fd.revents & POLLIN);
    }
    else if(event_num == 0)
    {
      errno = EAGAIN;
    }
    else
    {
      /// do nothing
    }
  }
  return result;
}

int64_t LinuxNetworkUtility::ul_gettimeofday()
{
  struct timeval now;
  gettimeofday(&now, NULL);
  return now.tv_sec*1000000 + now.tv_usec;
}
